<template>
    <el-dialog
            :title="title"
            :visible="show"
            width="50%"
            :close-on-click-modal="false"
            :before-close="closeDialog"
            @open="openAction"
    >
        <el-form
                ref="userForm"
                :model="userForm"
                :rules="rules"
                label-width="120px"
                style="width: 400px"
                size="mini">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="userForm.username" autocomplete="off" :disabled="!add"></el-input>
            </el-form-item>
            <el-form-item label="密码"
                          prop="password"
                          :rules="add?rules.password:[{required:false}]"
                          v-if="add"
            >
                <el-input v-model="userForm.password" show-password autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="重复输入密码"
                          prop="rePassword"
                          :rules="add?rules.rePassword:[{required:false}]"
                          v-if="add"
            >
                <el-input v-model="userForm.rePassword" show-password></el-input>
            </el-form-item>
            <el-form-item label="姓名" prop="name">
                <el-input v-model="userForm.name"></el-input>
            </el-form-item>
            <el-form-item label="手机号码" prop="phone">
                <el-input  v-model="userForm.phone"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="userForm.email"></el-input>
            </el-form-item>
            <el-form-item
                    label="是否可用"
                    prop="enabled"
                    v-if="!add"
                    :rules="!add?rules.enabled:[{required: false}]"
            >
                <dict-select
                        codeName="enabled"
                        :dictValue.sync="userForm.enabled"
                />
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
           <el-button type="primary" @click="saveUser('userForm')">保存</el-button>
           <el-button @click="closeDialog">关闭</el-button>
        </span>
    </el-dialog>
</template>

<script>
    import {updateUser} from "@/api/user";
    import {addUser} from "@/api/user";
    import DictSelect from "@/components/SysDictSelect";

    export default {
        name: "UserInfoEditor",
        components:{
            DictSelect
        },
        props:{
            title:{type:String,default:"用户编辑"},
            show:{type: Boolean},
            add:{type:Boolean,default: true},//判断是新增还是修改，用于显示和禁用某些输入项
            userInfo:{type:Object}
        },
        data(){
            let validatePass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入密码'));
                } else {
                    if (this.userForm.rePassword !== '') {
                        this.$refs['userForm'].validateField('rePassword');
                    }
                    callback();
                }
            };
            let validatePass2 = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入密码'));
                } else if (value !== this.userForm.password) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            };
            return {
                //表单属性
                userForm:{
                    username:"",
                    password:"",
                    rePassword:"",
                    name:"",
                    phone:"",
                    email:"",
                    enabled:""
                },
                //表单规则
                rules:{
                    username:[
                        {required:true,message:"账户名不能为空",trigger:'blur'}
                    ],
                    password:[
                        {required:true,message:"密码不能为空",trigger:'blur'},
                        { validator: validatePass, trigger: 'blur' }
                    ],
                    rePassword:[
                        {required:true,message:"密码不能为空",trigger:'blur'},
                        { validator: validatePass2, trigger: 'blur' }
                    ],
                    name:[
                        {required:true,message:"姓名不能为空",trigger:'blur'}
                    ],
                    phone:[
                        {required:true,message:"手机不能为空",trigger:'blur'},
                        {pattern:"^[0-9]{11}$",message: "手机号码格式不正确",trigger: 'blur'}
                    ],
                    email:[
                        {required:true,message:"邮箱不能为空",trigger:'blur'},
                        {type:'email',message: "邮箱格式不符合",trigger:'blur'}
                    ],
                    enabled:[
                        {required:true,message:"是否可用不能为空",trigger:"change"}
                    ]
                }
            }
        },
        methods:{
            //保存用户
            saveUser(){
                let that_ = this
                this.$refs['userForm'].validate((valid) => {
                    if (valid) {
                        // alert('submit!');
                        if(that_.add){
                            addUser(that_.userForm)
                                .then(res =>{
                                    that_.$message({
                                        type:"success",
                                        message:"保存成功！"
                                    })
                                    //成功后关闭窗口
                                    that_.closeDialog();
                                }).catch(err =>{
                                that_.$message({
                                        type:"error",
                                        message:err.message
                                    })
                            })
                        }else{
                            updateUser(that_.userForm)
                                .then(res =>{
                                    that_.$message({
                                        type:"success",
                                        message:"保存成功！"
                                    })
                                    //成功后关闭窗口
                                    that_.closeDialog();
                                }).catch(err =>{
                                that_.$message({
                                    type:"error",
                                    message:err.message
                                })
                            })
                        }
                    } else {
                        return false;
                    }
                });
            },
            //关闭窗口
            closeDialog(){
                this.$emit("update:show",false);
                this.$emit("refreshUser")
            },
            //打开窗口的初始化动作
            openAction(){
                this.$nextTick(()=>{
                    //清空表单
                    this.$refs.userForm.resetFields();
                    //解构赋值
                    this.userForm = {...this.userInfo}
                })
            }
        },
    }
</script>

<style scoped>

</style>